package com.ygqh.baby.service.wechat.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.model.WeixinPayAccount;
import com.foxinmy.weixin4j.mp.api.MpApi;
import com.foxinmy.weixin4j.util.DigestUtil;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.xml.XmlStream;
import com.ygqh.baby.service.wechat.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 报关接口
 *
 * @author (guohao)
 * @version V1.0
 * @ClassName: CustomsApi
 * @date 2018年11月19日 下午6:38:44
 */
@Component
public class CustomsApi extends MpApi {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     *
     */
    private final static String api_url = "https://api.mch.weixin.qq.com/cgi-bin/mch/customs/customdeclareorder";
    private final static String query_api_url = "https://api.mch.weixin.qq.com/cgi-bin/mch/customs/customdeclarequery";
    private final static String CUSTOM_DECLARERE_DECLARE = "https://api.mch.weixin.qq.com/cgi-bin/mch/newcustoms/customdeclareredeclare";

    public DeclareCustomsResult declareCustoms(WxDeclareCustoms customs, WeixinPayAccount wxPayAccount) throws WeixinException {
        customs.setAppid(wxPayAccount.getId());
        customs.setMchId(wxPayAccount.getMchId());

        if (StringUtil.isBlank(customs.getSign())) {
            customs.setSign(DigestUtil.paysignMd5(customs, wxPayAccount.getPaySignKey()));
        }
        logger.info("微信申报海关 -> request：" + JSON.toJSONString(customs));

        String payJsRequestXml = XmlStream.toXML(customs);
        WeixinResponse response = weixinExecutor.post(api_url, payJsRequestXml);

        logger.info("微信申报海关 -> response：" + response.getAsString());
        DeclareCustomsResult result = this.getAsObject(response.getAsString(), new TypeReference<DeclareCustomsResult>() {
        });

        if (!result.getReturnCode().equalsIgnoreCase(Consts.SUCCESS)) {
            logger.warn("微信申报海关失败。{}", response.getAsString());
            throw new WeixinException(result.getReturnCode(), result.getReturnMsg());
        }
        if (!result.getResultCode().equalsIgnoreCase(Consts.SUCCESS)) {
            logger.warn("微信申报海关失败。{}", response.getAsString());
            throw new WeixinException(result.getResultCode(), result.getErrCodeDes());
        }
        if (!result.getResultCode().equalsIgnoreCase(Consts.SUCCESS)) {
            logger.warn("微信申报海关失败。{}", response.getAsString());
            throw new WeixinException(result.getResultCode(), result.getErrCodeDes());
        }
        if (result.getState().equals("EXCEPT") || result.getState().equals("FAIL")) {
            logger.warn("微信申报海关失败。{}", response.getAsString());
            throw new WeixinException(result.getResultCode(), result.getState());
        }
        return result;

    }

    /**
     * 重推海关
     *
     * @param customs
     * @param wxPayAccount
     * @return
     * @throws WeixinException
     */
    public DeclareCustomsResult declareDeclareCustoms(WxCustomDelarereDeclare customs, WeixinPayAccount wxPayAccount) throws WeixinException {
        customs.setAppid(wxPayAccount.getId());
        customs.setMchId(wxPayAccount.getMchId());

        if (StringUtil.isBlank(customs.getSign())) {
            customs.setSign(DigestUtil.paysignMd5(customs, wxPayAccount.getPaySignKey()));
        }
        logger.info("微信重新申报海关 -> request：" + JSON.toJSONString(customs));

        String payJsRequestXml = XmlStream.toXML(customs);
        WeixinResponse response = weixinExecutor.post(CUSTOM_DECLARERE_DECLARE, payJsRequestXml);

        logger.info("微信重新申报海关 -> response：" + response.getAsString());
        DeclareCustomsResult result = this.getAsObject(response.getAsString(), new TypeReference<DeclareCustomsResult>() {
        });
        if (!result.getReturnCode().equalsIgnoreCase(Consts.SUCCESS)) {
            logger.warn("微信重新申报海关。{}", response.getAsString());
            throw new WeixinException(result.getReturnCode(), result.getReturnMsg());
        }
        if (!result.getResultCode().equalsIgnoreCase(Consts.SUCCESS)) {
            logger.warn("微信重新申报海关。{}", response.getAsString());
            throw new WeixinException(result.getResultCode(), result.getErrCodeDes());
        }
        if (!result.getResultCode().equalsIgnoreCase(Consts.SUCCESS)) {
            logger.error("微信重新申报海关。{}", response.getAsString());
            throw new WeixinException(result.getResultCode(), result.getErrCodeDes());
        }
        if (result.getState().equals("EXCEPT") || result.getState().equals("FAIL")) {
            logger.warn("微信重新申报海关。{}", response.getAsString());
            throw new WeixinException(result.getResultCode(), result.getState());
        }
        return result;
    }

    public QueryCustomsResult queryCustoms(WxQueryCustoms queryCustoms, WeixinPayAccount wxPayAccount) {
        queryCustoms.setAppid(wxPayAccount.getId());
        queryCustoms.setMchId(wxPayAccount.getMchId());
        queryCustoms.setSignType("MD5");

        if (StringUtil.isBlank(queryCustoms.getSign())) {
            queryCustoms.setSign(DigestUtil.paysignMd5(queryCustoms, wxPayAccount.getPaySignKey()));
        }
        String payJsRequestXml = XmlStream.toXML(queryCustoms);
        try {
            WeixinResponse response = weixinExecutor.post(query_api_url, payJsRequestXml);
            System.out.println(response.getAsString());
            return this.getAsObject(response.getAsString(), new TypeReference<QueryCustomsResult>() {
            });
        } catch (WeixinException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> T getAsObject(String StrXml, TypeReference<T> typeReference) {

        @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) typeReference.getType();
        return XmlStream.fromXML(StrXml, clazz);
    }
}
